package com.hzk.encrypte.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @Author hzk15
 * @Date 2022/4/1
 * @Verson 1.0
 **/
public class AESUtil {

    public static final String KEY_ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    public static final Pattern check = Pattern.compile("(\r\n|\r|\n|\n\r)");

    private static final String key = "hzkdecryptekey";

    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key skeySpec = genSecretKey(AESUtil.key.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes("utf-8"));
        //此处使用BASE64做转码
        String result=new BASE64Encoder().encode(encrypted);
        Matcher m = check.matcher(result);
        if(m.find()){
            result=m.replaceAll("");
        }
        return result;
    }

    // 解密
    public static String decrypt(String sSrc,String key) throws Exception {
        Key skeySpec = genSecretKey(AESUtil.key.getBytes());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, "utf-8");
        return originalString;
    }
    /**
     * AES only supports key sizes of 16, 24 or 32 bytes
     */
    public static Key genSecretKey(byte[] key) throws Exception {
        if (key.length == 16 || key.length == 24 || key.length == 32) {
            return new SecretKeySpec(key, KEY_ALGORITHM);
        }
        throw new IllegalArgumentException("AES only supports key sizes of 16, 24 or 32 bytes");
    }
}
